<template>
  <div class="search-container">
    <form action="/" class="sear-bar">
  <van-search
    v-model="kw"
    show-action
    placeholder="请输入搜索关键词"
     background="#3296FA"
    @search="onSearch"
    @cancel="onCancel"
    @focus="showResult = false"
  />
</form>
    <search-history v-if="!kw" :list="historyList" @search="searchSuggestion"></search-history>
    <search-suggestion v-if="kw && !showResult" :kw="kw" @search="searchSuggestion"></search-suggestion>
    <search-result  v-if="showResult" :kw="kw"></search-result>
  </div>
</template>

<script>
import searchHistory from './comments/search-history.vue'
import SearchResult from './comments/search-result.vue'
import SearchSuggestion from './comments/search-suggestion.vue'
import { setItem, getItem } from '@/utils/setToken'
const TOUTIAO_HISTORY = 'TOUTIAO_SEARCH_HISTORY'
export default {
  components: { searchHistory, SearchResult, SearchSuggestion },
  name: 'search',
  data () {
    return {
      kw: '',
      showResult: false,
      historyList: getItem(TOUTIAO_HISTORY) || []
    }
  },
  watch: {
    historyList (v) {
      setItem(TOUTIAO_HISTORY, this.historyList)
    }
  },
  methods: {
    onSearch () {
      this.showResult = true
      const index = this.historyList.indexOf(this.kw)
      if (index !== -1) {
        this.historyList.splice(index, 1)
      }
      this.historyList.unshift(this.kw)
    },
    onCancel () {
      this.$router.push('/')
    },
    searchSuggestion (v) {
      this.kw = v
      this.onSearch()
    }
  }
}
</script>

<style lang="scss" scoped>
  .search-container{
    padding-top: 108px;
    .sear-bar{
      position: fixed;
      top:0;
      left: 0;
      right: 0;
      z-index: 1;
    }
    .van-search__action {
      color: #fff;
      font-size: 28px;
    }
    ::v-deep .van-field__control{
      color:#969799;
    }
  }
</style>
